package cc.yugu.yhdw.common.tool.memcached;

import com.whalin.MemCached.MemCachedClient;
import com.whalin.MemCached.SockIOPool;
import org.apache.commons.lang.StringUtils;

import java.util.Date;
/**
 * memcache 配置参数
 *
 * @Date:Created in 2018/7/2 13:35
 * @Author:
 * @Modified By: zxj 2018/7/2 13:35
 */
public class MemCachedConfig {

    public static void main(String[] args) throws InterruptedException {
        MemCachedConfig config = new MemCachedConfig("localhost:11211:1");
        MemCachedClient client = MemCachedClientFactory.build(config);
        client.set("aaa", "aaa", new Date(11L * 1 * 1000));
        Thread.sleep(10 * 1000);
        System.out.println(client.get("aaa"));
        Thread.sleep(2 * 1000);
        System.out.println(client.get("aaa"));
    }

    public static final Date CACHE_TEN_SECOND = new Date(10 * 1000);
    public static final Date CACHE_ONE_HOUR = new Date(3600L * 1000);
    public static final Date CACHE_TWO_HOUR = new Date(3600L * 1000 * 2 + 1000 * 60);
    public static final Date CACHE_ONE_DAY = new Date(3600L * 24 * 1000);
    public static final Date CACHE_ONE_MINUTE = new Date(60L * 1 * 1000);
    public static final Date CACHE_FIVE_MINUTE = new Date(60L * 5 * 1000);
    public static final Date CACHE_ONE_WEEK = new Date(3600L * 24 * 7 * 1000);

    public static final Date CACHE_FOREVER = null;

    public MemCachedConfig() {
    }

    /**
     * @param url 格式: ip:port:weight,ip:port:weight,ip:port:weight
     */
    public MemCachedConfig(String url) {
        if(StringUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is empty");
        }

        String[] array = StringUtils.split(url, ",");
        servers = new String[array.length];
        weights = new Integer[array.length];

        for(int i = 0; i < array.length; i++) {
            String e = array[i];
            int index = e.lastIndexOf(':');
            servers[i] = e.substring(0, index);
            weights[i] = Integer.parseInt(e.substring(index + 1));
        }
    }

    public String[] servers;
    public Integer[] weights;

    int initialConnections = 10;
    int minSpareConnections = 5;
    int maxSpareConnections = 50;
    int maxIdleTime = 1000 * 60 * 30; // 30 minutes
    int maxBusyTime = 1000 * 60 * 5; // 5 minutes
    int maintThreadSleep = 1000 * 5; // 5 seconds
    int socketTimeOut = 1000 * 3; // 3 seconds to block on reads
    int socketConnectTimeout = 1000 * 3; // 3 seconds to block on initial connections. If 0, then will use blocking connect (default)
    boolean failover = false; // turn off auto-failover in event of server down
    boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in pool
    boolean aliveCheck = false; // disable health check of socket on checkout
    int hashingAlg = SockIOPool.NEW_COMPAT_HASH;
}
